/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package unilearn.bo;

import java.util.List;
import unilearn.dao.PersonDAO;
import unilearn.dao.PersonRoleDAO;
import unilearn.dao.RoleDAO;
import unilearn.vo.Person;
import unilearn.vo.PersonRole;
import unilearn.vo.Role;

/**
 *
 * @author Yat
 */
public class AccessValidator {

    private PersonDAO personDAO;
    private RoleDAO roleDAO;
    private PersonRoleDAO personRoleDAO;

    public AccessValidator() {
        personDAO = null;
        roleDAO = null;
        personRoleDAO = null;
    }

    public AccessValidator(PersonDAO personDAO, RoleDAO roleDAO, PersonRoleDAO personRoleDAO) {
        this();
        this.personDAO = personDAO;
        this.roleDAO = roleDAO;
        this.personRoleDAO = personRoleDAO;
    }

    public void setPersonDAO(PersonDAO personDAO) {
        this.personDAO = personDAO;
    }

    public void setPersonRoleDAO(PersonRoleDAO personRoleDAO) {
        this.personRoleDAO = personRoleDAO;
    }

    public void setRoleDAO(RoleDAO roleDAO) {
        this.roleDAO = roleDAO;
    }

    public Person validate(String id, String pw) throws Exception {
        Person person = null;
        List<Person> ps = null;

        ps = personDAO.getAll();
        for (Person p : ps) {
            if (p.getEmail().equals(id)) {
                person = p;
                break;
            }
        }

        if (person == null) {
            throw new Exception("Could not find this account(" + id + ").");
        }

        if (!person.getPassword().equals(pw)) {
            throw new Exception("Wrong Password.");
        }

        return person;
    }

    public Role getRole(Person person) throws Exception {
        PersonRole pr = new PersonRole();
        pr.setPersonId(person.getId());
        List<PersonRole> prs = personRoleDAO.find(pr);
        if ((prs == null) || (prs.isEmpty())) {
            return null;
        }

        Role role = roleDAO.get(prs.get(0).getRoleId());
        if (role == null) {
            throw new Exception("Could not find this person role.");
        }

        return role;
    }
}
